<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('form.excelImport.title')"
    append-to-body
    width="1100"
  >
    <el-steps
      :active="currentStep"
      align-center
      finish-status="success"
      simple
    >
      <el-step :title="$t('form.excelImport.step1')" />
      <el-step :title="$t('form.excelImport.step2')" />
      <el-step :title="$t('form.excelImport.step3')" />
    </el-steps>

    <!-- 步骤1：文件上传 -->
    <div
      v-if="currentStep === 1"
      class="step-content"
    >
      <el-upload
        :auto-upload="false"
        :limit="1"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        accept=".xls,.xlsx"
        class="upload-file"
        drag
      >
        <template v-if="!isParsingExcel">
          <el-icon class="el-icon--upload">
            <ele-UploadFilled />
          </el-icon>
          <div class="upload-text">
            <em>{{ $t("form.excelImport.dragFile") }}</em>
            <em>{{ $t("form.excelImport.clickUpload") }}</em>
          </div>
        </template>
        <template v-else>
          <div class="parsing-status">
            <el-icon class="loading">
              <ele-Loading />
            </el-icon>
            <p>{{ $t("form.excelImport.parseExcelLoading") }}</p>
          </div>
        </template>
        <template #tip>
          <div class="el-upload__tip">
            <p>{{ $t("form.excelImport.supportFormat") }}</p>
            <p>{{ $t("form.excelImport.mergedCellTip") }}</p>
            <p>{{ $t("form.excelImport.fileSizeTip") }}</p>
            <p>{{ $t("form.excelImport.dataLimitTip") }}</p>
          </div>
        </template>
      </el-upload>
    </div>

    <!-- 步骤2：表单设置 -->
    <div
      v-if="currentStep === 2"
      class="step-content"
    >
      <el-form
        :model="formSettings"
        label-width="120px"
      >
        <el-form-item
          :label="$t('form.excelImport.formName')"
          required
        >
          <el-input
            v-model="formSettings.name"
            :placeholder="$t('form.excelImport.formNamePlaceholder')"
          />
        </el-form-item>
        <!-- 列映射配置 -->
        <div class="column-mapping">
          <div class="mapping-header">
            <h3>{{ $t("form.excelImport.selectColumns") }}</h3>
          </div>
          <el-table
            ref="tableRef"
            :data="columnMappings"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              :label="$t('form.excelImport.excelColumnName')"
              prop="excelColumn"
            />
            <el-table-column :label="$t('form.excelImport.dataType')">
              <template #default="{ row }">
                <el-select v-model="row.dataType">
                  <el-option
                    :label="$t('formgen.config.INPUT')"
                    value="INPUT"
                  />
                  <el-option
                    :label="$t('formgen.config.TEXTAREA')"
                    value="TEXTAREA"
                  />
                  <el-option
                    :label="$t('formgen.config.RADIO')"
                    value="RADIO"
                  />
                  <el-option
                    :label="$t('formgen.config.CHECKBOX')"
                    value="CHECKBOX"
                  />
                  <el-option
                    :label="$t('formgen.config.SELECT')"
                    value="SELECT"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('form.excelImport.sampleValue')"
              prop="sampleValue"
            />
          </el-table>
        </div>
      </el-form>
    </div>

    <!-- 步骤3：导入结果 -->
    <div
      v-if="currentStep === 3"
      class="step-content"
    >
      <div class="import-result">
        <el-result
          :icon="importResult.success ? 'success' : 'error'"
          :sub-title="importResult.message"
          :title="importResult.success ? $t('form.excelImport.importSuccess') : $t('form.excelImport.importFailed')"
        ></el-result>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ $t("form.excelImport.cancel") }}</el-button>
        <el-button
          v-if="currentStep > 1 && currentStep < 3"
          @click="currentStep--"
        >
          {{ $t("form.excelImport.previous") }}
        </el-button>
        <el-button
          v-if="currentStep !== 1 && !(currentStep === 3 && !importResult.success)"
          :disabled="!canProceed"
          type="primary"
          @click="handleNextStep"
        >
          {{ currentStep === 3 ? $t("form.excelImport.view") : $t("form.excelImport.confirmImport") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import type { UploadFile } from "element-plus";
import { importExcelRequest, parseExcelRequest } from "@/api/project/template";
import { useComponents } from "@/views/formgen/components/FormDesign/hooks/useComponents";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(["update:visible"]);
const router = useRouter();

const dialogVisible = ref(props.visible);
const currentStep = ref(1);

// 添加文件列表状态
const fileList = ref<UploadFile[]>([]);

// 添加表单设置
const formSettings = ref({
  name: ""
});

// 添加解析状态
const isParsingExcel = ref(false);

// 控制下一步按钮的状态
const canProceed = computed(() => {
  if (currentStep.value === 1) {
    return fileList.value.length > 0;
  } else if (currentStep.value === 2) {
    return formSettings.value.name.trim() !== "";
  }
  return true;
});

watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
  }
);

watch(
  () => dialogVisible.value,
  val => {
    emit("update:visible", val);
    // 当对话框关闭时重置所有状态
    if (!val) {
      resetState();
    }
  }
);

const handleUploadSuccess = (response: any) => {
  dialogVisible.value = false;
  if (response.data) {
    const { formKey, type } = response.data;
    router.push({
      path: `/project/form/editor/index`,
      query: { key: formKey, active: "editor/index", type: type }
    });
  }
};

// 列映射数据结构
interface ColumnMapping {
  excelColumn: string;
  dataType: string;
  sampleValue: string;
  index: number;
}

const columnMappings = ref<ColumnMapping[]>([]);

const tableRef = ref<any>(null);

// 修改文件处理函数
const handleFileChange = async (file: UploadFile) => {
  fileList.value = [file];
  isParsingExcel.value = true;

  try {
    const formData = new FormData();
    if (file.raw) {
      // 获取文件名（去掉扩展名）
      const fileName = file.name.replace(/\.[^/.]+$/, "");
      // 设置为表单名称的默认值
      formSettings.value.name = fileName;

      formData.append("file", file.raw);
      // 发送请求解析Excel表头和示例数据
      const response = await parseExcelRequest(formData);
      if (response.data) {
        columnMappings.value = response.data.map((col: any) => ({
          excelColumn: col.excelColumn,
          dataType: "INPUT",
          sampleValue: col.sampleValue,
          index: col.index
        }));

        currentStep.value++;

        nextTick(() => {
          tableRef.value?.toggleAllSelection();
        });
      } else {
        ElMessage.error(response.message || "解析Excel失败");
      }
    }
  } catch (error) {
    ElMessage.error("解析Excel失败，请检查文件格式");
  } finally {
    isParsingExcel.value = false;
  }
};

// 处理文件移除
const handleFileRemove = () => {
  fileList.value = [];
};

const { getAllComponents } = useComponents();

const selectedColumnIds = ref<number[]>([]);
// 简化 handleSelectionChange 函数
const handleSelectionChange = (selection: ColumnMapping[]) => {
  selectedColumnIds.value = selection.map(col => col.index);
};

const importResult = ref({
  success: false,
  message: "",
  data: null
});

// 修改表单提交逻辑
const handleNextStep = async () => {
  if (currentStep.value === 2) {
    try {
      const formData = new FormData();
      if (fileList.value[0]?.raw) {
        formData.append("file", fileList.value[0].raw);
        formData.append("formName", formSettings.value.name);
        const blob = new Blob([JSON.stringify(getAllComponents(1).flatMap((item: any) => item.list))], { type: "text/plain" });
        formData.append("jsonSchema", blob);
        const selectedColumns = columnMappings.value
          .filter(col => selectedColumnIds.value.includes(col.index))
          .map(col => ({
            excelColumn: col.excelColumn,
            dataType: col.dataType,
            index: col.index
          }));
        formData.append("columnMappings", JSON.stringify(selectedColumns));

        const response = await importExcelRequest(formData);
        importResult.value = {
          success: response.code === 200,
          message: response.msg,
          data: response.data
        };
        currentStep.value = 3;
      }
    } catch (error) {
      importResult.value = {
        success: false,
        message: $t("form.excelImport.importFailedRetry"),
        data: null
      };
      currentStep.value = 3;
    }
  } else if (currentStep.value === 3) {
    dialogVisible.value = false;
    if (importResult.value.success) {
      handleUploadSuccess(importResult.value);
    }
  } else {
    currentStep.value++;
  }
};

// 添加重置状态的函数
const resetState = () => {
  currentStep.value = 1;
  fileList.value = [];
  formSettings.value.name = "";
  columnMappings.value = [];
  selectedColumnIds.value = [];
  importResult.value = {
    success: false,
    message: "",
    data: null
  };
  isParsingExcel.value = false;
};
</script>

<style lang="scss" scoped>
.upload-text {
  margin: 10px 0;

  em {
    font-style: normal;
    margin: 0 4px;
  }
}

.upload-file {
  width: 80%;
  margin: 0px auto;
}

.el-upload__tip {
  p {
    margin: 5px 0;
    color: var(--el-text-color-regular);
    font-size: 12px;
  }
}

.step-content {
  padding: 20px 0;
}

.import-result {
  padding: 20px;
  text-align: center;
}

.column-mapping {
  margin-top: 20px;

  .mapping-header {
    margin-bottom: 15px;

    h3 {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }
}

.el-table {
  margin-bottom: 20px;
}

.parsing-status {
  text-align: center;
  padding: 20px 0;

  .loading {
    font-size: 24px;
    margin-bottom: 10px;
    animation: rotating 2s linear infinite;
  }

  p {
    color: #909399;
    margin: 0;
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
